/**
 * Created by lmn98 on 2017/5/24.
 */
var express = require('express');
var router = express.Router();
var err = require('../my_modules/error.js');
var config = require('../config');
var db = require('../my_modules/my_sequlize');
var ffmpeg = require('../my_modules/main_ffmpeg');
var path = require('path');
var fs = require('fs');
var randomStr = require('../my_modules/randomStr');

//查看视频数据
router.post('/metadata', function (req, res) {
    var dir = req.body.dir;
    var name = req.body.name;
    if(!name) res.json(err.paraErr);
    else{
        try{
            var filePath = path.resolve(req.session.root+dir.replace(/\,/g,'/')+'/'+name);
            if(fs.existsSync(filePath))
                ffmpeg.metadata(filePath, function (data, e) {
                    if(data) res.json(data.streams);
                    else {
                        res.json(err.fileErr);
                    }
                });
            else
                res.json(err.fileNotExist)
        }catch (e){
            res.json(err.fileErr)
        }
    }
});

//建立视频转码任务
router.post('/', function (req, res) {
    if(!config.media.transcodingAvailable) {
        res.json(err.transcodeDisabled);
        return;
    }
    var fileList = req.body.list;
    var job = req.body.job;
    var save = req.body.save;
    var size = req.body.size || 480;
    var aspect = req.body.aspect || '';
    var start = req.body.start;
    var end = req.body.end;
    if(!fileList.length){
        res.json(err.paraErr);
        return;
    }
    for(var i=0,l=fileList.length;i<l;i++){
        var file = fileList[i];
        if(!file.name) continue;
        if(!file.dir) file.dir = '';
        var filePath = path.resolve(req.session.root+file.dir.replace(/\,/g,'/')+'/'+file.name);
        if(!fs.existsSync(filePath)) continue;
        var targetFileName = (job||'trans')+'_'+ file.name+'.mp4';
        var saveDir = file.dir.replace(/\,/g,'/') || req.session.dir;
        if(save)
            saveDir = '/'+save.replace(/\,/g, '/');
        var  savePath,workNo;
        if(job === 'backup'){
            workNo = randomStr.random(6)+'-'+new Date().getTime();
            savePath = path.resolve(req.session.root+saveDir);
            db.transcode.create({
                workNo: workNo,
                name: targetFileName,
                dir: saveDir,
                command: 2,
                state: 0,
                userId: req.session.userId
            });
            ffmpeg.screenShort(workNo, targetFileName, filePath, savePath);
        }
        workNo = randomStr.random(6)+'-'+new Date().getTime();
        savePath = path.resolve(req.session.root+saveDir+'/'+targetFileName);
        db.transcode.create({
            workNo: workNo,
            name: targetFileName,
            dir: saveDir,
            command: 1,
            state: 0,
            userId: req.session.userId
        });
        ffmpeg.transcoding(workNo, size, aspect, start, end, filePath, savePath);
    }
    res.json(err.success);
});

//查看转码任务列表
router.get('/list', function (req, res) {
    db.transcode.findAndCountAll({
        where: {
            userId: req.session.userId
        },
        limit: req.query.limit ? req.query.limit*1 : 100,
        offset: req.query.offset ? req.query.offset*1 : 0
    }).then(function (msg) {
        msg.total = msg.count;
        res.json(msg);
    })
});

//删除任务记录、
router.delete('/', function(req, res){
    var workNos = req.query.workNos;
    if(!workNos) res.json(err.paraErr);
    else{
        var works = workNos.split(',');
        var querys = [];
        works.forEach(function(workNo){
            if(workNo.length) querys.push(workNo);
        });
        db.transcode.destroy({
            where: {
                workNo: {
                    in: querys
                }
            }
        }).then(function (msg) {
            res.json(msg);
        })
    }
});

//停止转码任务
router.put('/:no', function (req, res) {
    ffmpeg.stopWork(req.params.no, function () {
        res.json(err.success);
    })
});

module.exports = router;